<template>
	<view class="content">
		<!-- :backgroundColor="backgroundColor" -->
		<uni-nav-bar title="订单详情" :fixed="true" :color="fontColor" :statusBar="true" :border="false"
			:backgroundColor="nav_opacity" left-icon="left" leftText="返回" :placeholder="false" @clickLeft="clickLeft">
		</uni-nav-bar>

		<!-- 顶部背景 -->
		<view class="tang-feng-bg"></view>
		<!--内容区 -->
		<view class="tang-feng-block">
			<!-- 用户数据块 -->
			<view class="tang-feng-data">
				<view class="detail-top">
					<view class="detail-top-1">
						<image src="/static/detail/jinxi.png" mode="widthFix"></image>
						待支付
					</view>
					<view class="detail-top-2">离结束时间还有5个小时</view>
				</view>
				<!-- 地址信息 -->
				<template v-if="shopData.orderType == 'takein'">
					<view class="detailitem detail-address">
						<view class="top">
							<image src="/static/detail/address.png" mode="widthFix"></image>
							{{shopData.shopName}}
						</view>
						<view class="address">地址：{{shopData.shopAddress}}</view>
					</view>
				</template>
				<template v-else>
					<view class="detailitem detail-address" @click="toAddress">
						<view class="top">
							<image src="/static/detail/address.png" mode="widthFix"></image>
							{{userOrderAddress.receiverName}} {{userOrderAddress.receiverPhone}}
						</view>
						<view class="address">地址：{{userOrderAddress.addressDetail}}</view>
					</view>
				</template>


				<!-- 商品信息 -->
				<view class="detailitem shopBox">
					<view class="item" v-for="(item,index) in orderData" :key="index">
						<image :src="getImgUrl+item.image" mode="widthFix"></image>
						<view class="conBox">
							<view class="conBox-1">{{item.name}}</view>
							<view class="conBox-2">{{item.props_text}}</view>
							<view class="conBox-3">¥ {{item.price}}</view>
						</view>
						<view class="number">x{{item.number}}</view>
					</view>
				</view>
				<!-- 订单信息 -->
				<view class="detailitem orderItem">
					<!-- <view class="orderItem-min">
						<view class="orderItem-1">订单编号：</view>
						<view class="orderItem-2">25254532545255</view>
						<view class="orderItem-3" @click="copyText('25254532545255')">复制</view>
					</view> -->
					<!-- 	<view class="orderItem-min">
						<view class="orderItem-1">下单时间：</view>
						<view class="orderItem-2">2024-04-10 18:36:41</view>
					</view> -->
					<view class="orderItem-min">
						<view class="orderItem-1">配送方式：</view>
						<view class="orderItem-2" v-if="shopData.orderType == 'takein'">自提</view>
						<view class="orderItem-2" v-else>外卖</view>
					</view>
					<view class="orderItem-min">
						<view class="orderItem-1">买家留言：</view>
						<view class="orderItem-2">无</view>
					</view>
					<view class="orderItem-min" style="border-bottom: 2rpx solid rgba(0,0,0,0)">
						<view class="orderItem-1">发票类型：</view>
						<view class="orderItem-2">不开发票</view>
					</view>
				</view>
				<!-- 订单信息 -->
				<view class="detailitem orderItem" style="margin-bottom: 100rpx;">
					<view class="orderItem-min orderInfo">
						<view class="orderItem-1">商品总额</view>
						<view class="orderItem-2">¥ {{shopMoneyTotal}}</view>
					</view>
					<view class="orderItem-min orderInfo">
						<view class="orderItem-1">运费</view>
						<view class="orderItem-2">+ ¥{{shopData.orderType == 'takein'?0:5}}</view>
					</view>
					<view class="orderItem-min orderInfo" style="border-bottom: 2rpx solid rgba(0,0,0,0)">
						<view class="orderItem-1"></view>
						<view class="orderItem-2">实付款：<text style="color: red;"> ¥{{shopMoneyTotal}}</text></view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部按钮 -->
		<view class="bottomBox">
			<view class="leftTxt">¥<text style="font-size: 46rpx;margin-left: 15rpx;">{{shopMoneyTotal}}</text> </view>
			<view class="gnBox">
				<!-- <view class="item zhun">转派</view>
				<view class="item jie">派单</view> -->
				<view class="item lianxi" @click="payMoney">支付</view>
			</view>
		</view>

		<pwdModal ref="tixian" @success="passSubmit" @forgetpassword="forgetpassword"> </pwdModal>
	</view>
</template>

<script setup>
	// import {Alert} from '@/utils/alert';
	import pwdModal from "@/uni_modules/uu-pwdModal/components/uu-pwdModal/uu-pwdModal.vue"
	import {
		ref,
		getCurrentInstance,
		reactive,
		computed,
		watch,
		toRefs
	} from "vue"
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';

	//用户仓库
	import {
		userInfo
	} from '../../stores/userInfo'

	let UserInfo = userInfo()

	let backgroundColor = ref(0)
	let nav_opacity = ref('rgba(255,255,255,0)')
	let fontColor = ref('#ffffff')

	//密码框属性
	let tixian = ref()
	// 支付密码
	let paypassworData = ref("123123")

	// 店铺id
	let shopAddId = ref(0)
	let orderData = ref([])
	let shopData = ref({}) //店铺信息，以及用户的点餐方式

	// 用户下单地址
	let userOrderAddress = ref({})


	//商品总金额
	let shopMoneyTotal = computed(() => {
		let total = 0;

		orderData.value.map(item => {
			total += item.price * item.number
		})
		// console.log(total,"total")
		return total.toFixed(2)
	})

	//提交密码
	let passSubmit = async (e) => {
		// console.log(e, "提交密码")
		let res = validatePassword(paypassworData.value, e)
		// console.log(res, "res支付")
		if (res) {

			// console.log(UserInfo.wxUserAccount.balance, Number(shopMoneyTotal.value), "金额")
			// if(UserInfo.wxUserAccount.balance)

			if (UserInfo.wxUserAccount.balance < Number(shopMoneyTotal.value)) {
				uni.showToast({
					title: '支付失败,余额不足', // 提示内容
					icon: 'error', // 图标类型：success、loading、none
					duration: 2000 // 显示时长（毫秒）
				});
				tixian.value.close()
			} else {
				// {
				//      userId:1,
				//      addressId:4,
				//      deliveryMethod:"配送",
				//      shopAddressId:3,
				//      notes:"不用放垃圾，少放盐",
				//      packecharge:10,
				//      items:[{
				//        productId:5,
				//        quantity:3
				//      },
				//      {
				//        productId:7,
				//        quantity:3
				//      },{
				//        productId:9,
				//        quantity:3
				//      }]
				//     }
				let userOrderData = {
					wxLoginCode: UserInfo.userinfoData.wxLoginCode,
					addressId: userOrderAddress.value?.id ? userOrderAddress.value.id : 0,
					deliveryMethod: shopData.value.orderType == "takein" ? "自提" : "配送",
					shopAddressId: shopData.value.id,
					notes: "",
					packecharge: 10,
					// items:[]

				}
				let goodsData = []
				orderData.value.map(item => {

					let obj = {
						productId: item.id,
						quantity: item.number
					}
					goodsData.push(obj)
				})

				userOrderData["items"] = JSON.stringify(goodsData)

				// console.log(userOrderData, "userOrderData")

				let result = await UserInfo.userOrderData(userOrderData)

				

				// console.log(result, "result")
				if (result.code == 200) {
					uni.showToast({
						title: '支付成功', // 提示内容
						icon: 'success', // 图标类型：success、loading、none
						duration: 2000 // 显示时长（毫秒）
					});
					
					uni.removeStorageSync('cart');
					
					uni.switchTab({
						url: '/pages/mine/orderList'
					});
				}else{
					uni.showToast({
						title: '支付失败', // 提示内容
						icon: 'error', // 图标类型：success、loading、none
						duration: 2000 // 显示时长（毫秒）
					});
				}

			}


		} else {
			uni.showToast({
				title: '支付失败,密码错误', // 提示内容
				icon: 'error', // 图标类型：success、loading、none
				duration: 2000 // 显示时长（毫秒）
			});
		}
	}


	let validatePassword = (targetPassword, inputArray) => {
		// 基本匹配检查
		if (!isPasswordMatch(targetPassword, inputArray)) {
			return false;
		} else {
			return true;
		}


	}

	let isPasswordMatch = (targetPassword, inputArray) => {
		// 将目标密码转换为字符串形式
		const targetString = String(targetPassword);

		// 将输入的密码数组转换为字符串形式
		const inputString = inputArray.join("");
		console.log(targetString, inputString, "inputString")
		// 比较两者是否相等
		return targetString == inputString;
	}


	// 导航栏渐变
	let onPageScroll = (e) => {
		nav_opacity.value = `rgba(255,255,255,${(e.scrollTop > 255 ? 255 : e.scrollTop) / 255})`;
		if (e.scrollTop > 20) {
			fontColor.value = '#000000'
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: '#ffffff',
			})
		} else {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: '#ffffff'
			})
			fontColor.value = '#ffffff'
		}
	}
	// onLoad() 


	//支付按钮
	let payMoney = () => {
		console.log("支付")
		tixian.value.open()
	}


	// 获取图片地址
	let getImgUrl = computed(() => {
		return UserInfo.getimgUrl()
	})

	let clickLeft = () => {
		uni.navigateBack({
			delta: 1
		})
	}
	/**
	 * @function 复制功能
	 */
	let copyText = (msg) => {
		uni.setClipboardData({
			data: msg,
			success: () => {

				uni.showToast({
					icon: 'success',
					title: '复制成功'
				});
			},
			fail: () => {


				uni.showToast({
					icon: 'success',
					title: '复制失败'
				});
			}
		});

	}

	let init = () => { //页面初始化


		let results = uni.getStorageSync('cart') || []
		// console.log("resultsfefesfse")
		// console.log(results.ShopId == shopAddId.value,results.ShopId , shopAddId.value,"真的没有调用吗fesfs封杀封杀")
		if (results.ShopId == shopAddId.value) {
			orderData.value = results.data

			// console.log(orderData.value, "orderDatadwfwafaw")
		}
	}

	// 获取用户外卖地址
	// watch(()=>shopData.value.orderType,(news,ord)=>{

	// 	if(news=="takeout"){
	// 		let results = uni.getStorageSync('userOrderAddress') || []
	// 		userOrderAddress.value = results
	// 		console.log(results,"results这是王小磊")
	// 	}

	// 	// console.log(news,"news,ord")
	// })

	// 获取用户外卖地址
	let getUserOrderAddress = () => {
		if (shopData.value.orderType == "takeout") {
			let results = uni.getStorageSync('userOrderAddress') || []
			userOrderAddress.value = results
			console.log(results, "results这是王小磊")
		}
	}

	//跳到地址页
	let toAddress = () => {
		uni.navigateTo({
			url: "/pages/mine/addressList"
		})
	}

	//获取传过来的shopId
	onLoad((option) => {
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel();
		eventChannel.on('emitShopAddress', async (data) => {
			console.log(data.data, "这是传过来的店铺idfwafawfwa符文啊福娃")
			shopAddId.value = data.data.id
			shopData.value = data.data
			init()

		})

	})

	onShow(() => {
		console.log("无论什么跳转都显示")
		getUserOrderAddress()
	})
</script>

<style lang="scss">
	.content {
		color: #010101;
		font: normal 14px/2.2 Arial, Verdana, Tahoma, sans-serif;
		background-color: #F5F5F5;
	}

	.tang-feng-bg {
		width: 100%;
		height: 700rpx;
		position: relative;
		background: linear-gradient(to top, #ff0000, #ff4500);
	}

	.tang-feng-block {
		padding: 20rpx;
		box-sizing: border-box;
		margin-top: -520rpx;
		position: relative;
		z-index: 3;

		.tang-feng-data {
			border-radius: 12rpx;
			margin-bottom: 20rpx;

			.detail-top {
				width: 100%;
				margin-bottom: 20rpx;

				.detail-top-1 {
					color: #ffffff;
					font-weight: bold;
					font-size: 46rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					image {
						width: 70rpx;
						height: 65rpx;
						margin-right: 10rpx;
					}
				}

				.detail-top-2 {
					color: #ffffff;
					font-size: 32rpx;
					text-align: center;
					letter-spacing: 3rpx;
				}
			}

			.detailitem {
				background-color: #ffffff;
				border-radius: 20rpx;
				box-shadow: 0 0upx 6upx 0upx rgba(0, 0, 150, .2);
				margin-bottom: 20rpx;
				padding: 20rpx;
				box-sizing: border-box;
			}

			.detail-address {
				.top {
					font-weight: bold;
					letter-spacing: 3rpx;
					font-size: 32rpx;
					display: flex;
					align-items: center;

					image {
						width: 40rpx;
						height: 40rpx;
						margin-right: 10rpx;
					}
				}

				.address {
					color: rgba(0, 0, 0, .7);
				}
			}

			.shopBox {

				// height: 200rpx;
				.item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;

					image {
						width: 200rpx;
						height: 200rpx;
						border-radius: 10rpx;
					}

					.conBox {
						flex: 1;
						min-height: 200rpx;
						padding: 10rpx 20rpx;
						box-sizing: border-box;
						border-bottom: 2rpx solid #f3f3f3;

						.conBox-1 {
							font-size: 28rpx;
							font-weight: bold;
						}

						.conBox-2 {
							font-size: 22rpx;
							font-weight: bold;
							color: rgba(0, 0, 0, .7);
						}

						.conBox-3 {
							font-size: 34rpx;
							font-weight: bold;
							color: red;
						}
					}

					.number {
						width: 70rpx;
						text-align: center;
					}
				}
			}

			.orderItem {
				.orderItem-min {
					width: 100%;
					display: flex;
					align-items: center;
					letter-spacing: 4rpx;
					border-bottom: 2rpx solid #f3f3f3;
					padding: 15rpx 0;

					.orderItem-1 {
						width: 170rpx;
						color: rgba(0, 0, 0, .7);
					}

					.orderItem-2 {
						color: #000000;
						font-weight: bold;
						margin-right: 20rpx;
					}

					.orderItem-3 {
						padding: 0rpx 20rpx;
						box-sizing: border-box;
						border-radius: 10rpx;
						background-color: #eeeeee;
					}
				}

				.orderInfo {
					justify-content: space-between;
				}
			}
		}
	}

	.bottomBox {
		background-color: #ffffff;
		border: 1px solid #cccccc;
		/* 设置边框 */
		box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
		/* 设置阴影 */
		width: 750rpx;
		height: 140rpx;
		position: fixed;
		bottom: 0;
		z-index: 20;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 20rpx;
		box-sizing: border-box;
		letter-spacing: 5rpx;

		.leftTxt {
			color: #e55239;
			font-size: 40rpx;
			font-weight: bold;
		}

		.gnBox {
			height: 100%;
			display: flex;
			align-items: center;

			.item {
				// width: 70rpx;
				background-color: #e55239;
				color: #ffffff;
				padding: 0rpx 20rpx;
				box-sizing: border-box;
				margin-left: 15rpx;
				border-radius: 10rpx;
			}

			.zhun {
				background-color: #e55239;
			}

			.jie {
				background-color: #6b5ef8;
			}

			.lianxi {
				background-color: #51baad;
			}
		}
	}
</style>